package app.util;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import com.app.R;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.appbar.AppBarLayout.OnOffsetChangedListener;
import java.util.Arrays;
import java.util.Objects;

public class NestedScrollLayout extends TransferLayout
{
    public static boolean DEBUG = false;
    public VB vb;

    public NestedScrollLayout(Context context){
        super(context);
        init(context, null);
    }

    public NestedScrollLayout(Context context, AttributeSet attrs){
        super(context, attrs);
        init(context, attrs);
    }

    public NestedScrollLayout(Context context, AttributeSet attrs, int defStyleAttr){
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    void init(Context context, AttributeSet attrs){

    }

    @Override
    protected void onFinishInflate(){
        super.onFinishInflate();
        vb = new VB();
        vb.appBarLayout = findViewById(R.id.nsl_appBarLayout);
        vb.backstage = findViewById(R.id.nsl_backstage);
        vb.backstageMask = findViewById(R.id.nsl_backstageMask);
        vb.header = findViewById(R.id.nsl_header);
        vb.footer = findViewById(R.id.nsl_footer);
        setVB(vb);
    }

    public static void setVB(VB vb){
        vb.appBarLayout.addOnOffsetChangedListener(new OnOffsetChangedListener()
        {
            Integer mOffset;

            @Override
            public void onOffsetChanged(AppBarLayout layout, int offset){
                float ratio = -offset / (float)vb.backstage.getHeight();
                if(DEBUG) Log.i("----", "onOffsetChanged " + Arrays.asList(//
                    "offset",//
                    offset,//
                    "ratio",//
                    ratio,//
                    ""//
                ));
                if(!Objects.equals(mOffset, offset)){
                    boolean showIt = Objects.equals(mOffset, 0);
                    mOffset = offset;
                    if(showIt || offset == 0){
                        vb.footer.setVisibility(showIt? View.VISIBLE: View.GONE);
                    }
                }
                float threshold = 0.7f;
                float limit = 0.6f;
                if(ratio <= threshold) vb.backstageMask.setAlpha(ratio / threshold);
                if(ratio <= threshold * (1 - limit)) vb.header.setAlpha(ratio / threshold + limit);
            }
        });
    }

    public static class VB
    {
        public AppBarLayout appBarLayout;
        public View backstage;
        public View backstageMask;
        public View header;
        public View footer;
    }

}
